package com.magupe.netty.im.client.handler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 * ChannelInboundHandlerAdapter类的消息传递
 * 
 * @author m1873
 * @since 2020-06-07
 */
public class HelloClientHandlerAdapter extends ChannelInboundHandlerAdapter{

	protected Logger logger = LoggerFactory.getLogger(HelloClientHandlerAdapter.class);
	
	/**
	 * 当客户端和服务端 TCP链路建立成功之后，会调用该方法
	 */
	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
	    String reqMsg = "我是客户端 ";
	    byte[] reqMsgByte = reqMsg.getBytes("UTF-8");
	    ByteBuf buffer = Unpooled.buffer(reqMsgByte.length);
	    buffer.writeBytes(reqMsgByte);
	    
	    // 1. 获取二进制抽象 ByteBuf
        //ByteBuf buffer = ctx.alloc().buffer();
        // 2. 准备数据，指定字符串的字符集为 utf-8
        //byte[] bytes = "我是客户端 ".getBytes(Charset.forName("utf-8"));
        // 3. 填充数据到 ByteBuf
        //buffer.writeBytes(bytes);
	    
	    ctx.writeAndFlush(buffer);
	}

	/**
	 * 当服务端返回应答消息时，channelRead 方法被调用，从 Netty 的 ByteBuf 中读取并打印应答消息
	 */
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
	    ByteBuf buffer = (ByteBuf) msg;
	    byte[] req = new byte[buffer.readableBytes()];
	    buffer.readBytes(req);
	    String body = new String(req, "UTF-8");
	    // String body = buffer.toString(Charset.forName("utf-8")));
	    System.out.println(body);
	    
	    ctx.close();
	}

	/**
	 * 当发生异常时，打印异常 日志，释放客户端资源
	 */
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
	    /**释放资源*/
	    logger.warn("Unexpected exception from downstream : " + cause.getMessage());
	    ctx.close();
	}
}
